package cn.xin.pet.service.impl;

import cn.xin.pet.domain.PetType;
import cn.xin.pet.service.IPetTypeService;
import cn.xin.base.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xin
 * @since 2023-01-08
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Override
    public List<PetType> tree() {
        List<PetType> result = new ArrayList<>();

        //查询所有
        List<PetType> typeList = findAll();
        //把list集合转换为map
        Map<Long, PetType> map = typeList.stream().collect(Collectors.toMap(PetType::getId, e -> e));
        //遍历添加
        typeList.forEach(petType -> {
            if (petType.getPid() == null){
                //如果pid等于null，那它就是顶级的
                result.add(petType);
            }else {
                //传入父类的id，获取到父类的对象
                PetType type = map.get(petType.getPid());

                type.getChildren().add(petType);
            }
        });
        return result;
    }
}
